package com.monitor.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.ChargeConfigDao;
import com.config.dao.EquMoldDao;
import com.config.dao.EquStateConfigDao;
import com.config.dao.EquipmentDao;
import com.config.dao.LineConfigDao;
import com.config.dao.ShiftConfigDao;
import com.config.entity.ChargeConfig;
import com.config.entity.EquMold;
import com.config.entity.EquStateConfig;
import com.config.entity.Equipment;
import com.config.entity.LineConfig;
import com.config.entity.ShiftConfig;
import com.data.dao.BaseDataDao;
import com.data.dao.BaseDataDtoDao;
import com.data.dao.ChargeDayDao;
import com.data.entity.BaseDataDto;
import com.data.entity.ChargeDay;
import com.monitor.dao.MonitorDao;

@Service("monitorService")
public class MonitorServiceImpl implements MonitorService{
	@Resource(name="baseDataDao")
	private   BaseDataDao baseDataDao;
	@Resource(name="lineConfigDao")
	private LineConfigDao lineConfigDao;
	@Resource(name="equipmentDao")
	private  EquipmentDao equipmentDao;
	@Resource(name="shiftConfigDao")
	private ShiftConfigDao shiftConfigDao;
	@Resource(name="equStateConfigDao")
	private  EquStateConfigDao equStateConfigDao;
	@Resource(name="chargeConfigDao")
	private  ChargeConfigDao chargeConfigDao;
	@Resource(name="monitorDao")
	private MonitorDao monitorDao;
	@Resource(name="baseDataDtoDao")
	private   BaseDataDtoDao baseDataDtoDao;
	@Resource(name="chargeDayDao")
	private ChargeDayDao chargeDayDao;
	@Resource(name = "equMoldDao")
	private EquMoldDao equMoldDao;
	
	/**
	 * 动态刷新设备实时数据
	 * @param lineId
	 * @param equId
	 * @param model
	 */
	@Override
	public void getSingleMonitorData(int lineId, int equId, Map<String, Object> model) {
		Equipment equ=equipmentDao.get(equId);
		double startHour=0.0;//开工时长
		double overLoad=0.0;//超载时长(分钟)
		double currentPower=0.0;//当前功率
		String  shiftName="";//当前班次
		String now="";//当前时间
		String currentState="";//当前状态
		String equType="";//设备类型
		String photoPath=equ.getEquPhoto();
		String path="";
		
		if(photoPath!=null){
			path="/wz_ems/up/"+photoPath;
		}else{
			path="/wz_ems/resources/img/p1.png";
		}
		EquMold ed=equMoldDao.get(equ.getEquMoldId());
		if(ed!=null){
			equType=ed.getEquType();
		}
		
		List<Double> powers=new ArrayList<Double>();//实时功率
		List<String> times=new ArrayList<String>();//时间
		DecimalFormat  df=new DecimalFormat ("0.0");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfs = new SimpleDateFormat("HH:mm:ss");
		Calendar ca=Calendar.getInstance();
		String startdate=sdft.format(ca.getTime())+" "+"00:00:00";
		String currentdate=sdf.format(ca.getTime());
		
		double currentHour=ca.get(Calendar.HOUR_OF_DAY);
		double currentMin=ca.get(Calendar.MINUTE);
//		startHour=Double.parseDouble(df.format(currentHour+currentMin/60));
		//获取当前班次
//		ShiftConfig shift=shiftConfigDao.findShiftConfigByDate(lineId, ca.getTime());
//		if(shift!=null){
//			shiftName=shift.getShiftName();
//		}
		//单机实时功率  15秒数据 
		List<BaseDataDto> bases=baseDataDtoDao.getBaseDataDtoTopN(equ.getEquNo());
		//按照时间排序
		Collections.sort(bases, new Comparator<BaseDataDto>() {
			public int compare(BaseDataDto bd1, BaseDataDto bd2) {
				return bd1.getTime().compareTo(bd2.getTime());
			}
         });
		if(bases.size()!=0){
		    now=sdf.format(bases.get(bases.size()-1).getTime());
			currentPower=bases.get(bases.size()-1).getP_active();
			for(BaseDataDto base:bases){
				powers.add(base.getP_active());
				times.add(sdfs.format(base.getTime()));
			}
		}
		 //根据当前功率值获取设备当前状态
//		List<EquStateConfig> states=equStateConfigDao.findAll();
//		if(states.size()!=0){
//			for(EquStateConfig state:states){
//				if(currentPower>=state.getLowValue()&&currentPower<state.getHighValue()){
//					currentState=state.getStateType();
//					break;
//				}
//			}
//		}
		//计算超载时长
//		EquStateConfig estate=equStateConfigDao.getEquPowerValue("超载");
//		if(estate!=null){
//			overLoad=baseDataDao.getCountBaseDatasByDateAndPower(equ.getEquNo(),startdate , currentdate, estate.getLowValue(), estate.getHighValue());
//			overLoad=Double.parseDouble(df.format(overLoad/60));
//		}
		BaseDataDto bdd=this.getMachineData(equId,equ.getEquNo(), ca.getTime(),"N");
		String belongDate= sdf.format(new Date());
		//返回前台显示内容
		model.put("startHour", startHour+"小时");
		model.put("shiftName", shiftName);
		model.put("todayEngry", bdd.getMacEngry()+"度");
		model.put("todayCharges", bdd.getMacCharges()+"元");
		model.put("currentPower", currentPower);
		model.put("currentState", currentState);
		model.put("overLoad", overLoad+"分钟");
		model.put("ratedPower", equ.getRatedPower());
		model.put("equNo", equ.getEquNo());
		model.put("equName", equ.getEquName());
		model.put("equType", equType);
		model.put("now", now);
		model.put("powers", powers);
		model.put("times", times);
		model.put("path", path);
		model.put("belongDate",belongDate);
	}
	
	/**
	 * 动态刷新生产线实时数据
	 * @param lineId
	 * @param model
	 */
	@Override
	public void getlineMonitorData(int lineId, Map<String, Object> model) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<BaseDataDto> bdds=new ArrayList<BaseDataDto>();
		//定义前台显示字段
		double startHour=0.0;//开工时长
		String  shiftName="";//当前班次
		//计算开工时间
		Calendar ca=Calendar.getInstance();
		String now=sdf.format(ca.getTime());//当前时间
		LineConfig line=lineConfigDao.get(lineId);
		List<Equipment> equs=equipmentDao.listByLine(lineId);
		if(equs.size()!=0){
			for(Equipment e:equs){
				bdds.add(this.getMachineData(e.getId(), e.getEquNo(), ca.getTime(), "N"));
			}
		}
		//返回前台显示内容
		model.put("name", line.getName());
		model.put("startHour", startHour+"小时");
		model.put("shiftName", shiftName);
		model.put("now", now);
		model.put("singledata", bdds);
	}
	
	/**
	 * 计算设备实时刷新的共同数据
	 * @param id
	 * @return
	 */
	private  BaseDataDto getMachineData(int id,String leNo,Date date,String isLine){
		SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd HH");
		SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
		BaseDataDto bdd=new BaseDataDto();
		String nextdate="";//分界时间的下一秒时间
		String currentState="";//当前状态
		double todayEngry=0.0;//今日耗电
		double todayCharges=0.0;//今日电费
		double currentPower=0.0;//当前功率
		
		Calendar ca=Calendar.getInstance();
		ca.setTime(date);
		String startDate=sdft.format(ca.getTime());
		double currentMin=ca.get(Calendar.MINUTE);
		 //电费计算分两部分，一部分数据从chargeDay表中获取，另一部分从baseDataDto表中获取
		if(currentMin>=0&&currentMin<30){
			nextdate=sdt.format(ca.getTime())+":00:01";
		}else if(currentMin>=30){
			nextdate=sdt.format(ca.getTime())+":30:01";
		}
		//当前时间整点或半点电费
		double daycharges=0.0; double basecharges=0.0;double baseengry=0.0;double dayengry=0.0;
		ChargeDay cday=chargeDayDao.getCompAndChargeByType(id, startDate, startDate, "", isLine);
		if(cday!=null){
			daycharges=cday.getCharge();
			dayengry=cday.getRelativeComp();
		}
       	//到当前时间的记录
	    BaseDataDto currentbd=baseDataDtoDao.getLastBaseDataDto(leNo);
		if(currentbd!=null){
			currentPower=currentbd.getP_active();
			bdd.setI_a(currentbd.getI_a());
			bdd.setU_a(currentbd.getU_a());
			bdd.setP_active(currentPower);
		}else{
			currentPower=0.0;
			bdd.setI_a(0.0);
			bdd.setU_a(0.0);
			bdd.setP_active(currentPower);
		}
		
		Equipment e=equipmentDao.getByEquNo(leNo);
		bdd.setEquNo(leNo);
		if(e.getEquPhoto()!=null&&!"".equals(e.getEquPhoto())){
			bdd.setPath("/wz_ems/up/"+e.getEquPhoto());
		}else{
			bdd.setPath("/wz_ems/resources/img/p1.png");
		}
		//临界时间的后一秒
		BaseDataDto nextbd=baseDataDtoDao.getBaseDataDtoByEquNoAndDate(leNo, nextdate);
	   //获取当前耗电和当前功率
//		if(currentbd!=null){
//	    	if(nextbd!=null){
//	    		baseengry=currentbd.getP_engry()-nextbd.getP_engry();
//	    	}    
//	    	else{
//	    		baseengry=currentbd.getP_engry();
//	    	}
//	    }
		//整点或半点时间之后的电费
//		ChargeConfig config=chargeConfigDao.findByTime(ca.getTime());
//		if(config!=null){
//			basecharges=baseengry*config.getUnitValue();
//		}
		DecimalFormat  df=new DecimalFormat ("0.0");
		 //总电费
		todayCharges=Double.parseDouble(df.format(daycharges+basecharges));
		 //总耗电
		todayEngry=Double.parseDouble(df.format(dayengry+baseengry));
		if(todayEngry>=0){
			bdd.setMacEngry(todayEngry);
			bdd.setMacCharges(todayCharges);
		}else{
			bdd.setMacEngry(0.0);
			bdd.setMacCharges(0.0);
		}
		
		 //根据当前功率值获取设备当前状态
//		List<EquStateConfig> states=equStateConfigDao.findAll();
//		if(states.size()!=0){
//			for(EquStateConfig state:states){
//				if(currentPower>=state.getLowValue()&&currentPower<state.getHighValue()){
//					currentState=state.getStateType();
//					break;
//				}
//			}
//		}
		bdd.setMacStateType(currentState);
		return bdd;
	}
	/**
	 * 设备实时数据
	 * @param lineId
	 * @return
	 */
	@Override
	public List<BaseDataDto> findByLineId(int lineId) {
		List<Equipment> equs = equipmentDao.listByLine(lineId);
		StringBuffer cond = new StringBuffer();
		int equNum = equs.size();
		if(equs!=null && equNum>0){
			for(Equipment equ:equs){
				cond.append("'"+equ.getEquNo()+"',");
			}
		}else{
			return null;
		}
		return monitorDao.findByLineId(lineId, equNum, cond.toString().substring(0,cond.length()-1));
	}
}
